<?php
namespace Clover\Controller;

use Think\Controller;

class BannerController extends BaseController
{
    public function __construct()
    {
        parent::__construct();
        session('menu', "banner");
    }

    public function index()
    {
        check_privilege();
        $banner_list = M("Banner")->order("sort_order desc")->select();
        $data = array("banner_list" => $banner_list);
        $this->assign($data);
        $this->display("banner_list");


    }

    //上传cover
    public function upload_cover()
    {
        $upload = new \Think\UploadFile();// 实例化上传类
        $upload->maxSize = 5242880;// 5M设置附件上传大小
        $upload->allowExts = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
        $savepath = './Public/Uploads/' . date('Y-m-d') . '/';
        if (!file_exists($savepath)) {
            mkdir($savepath);
        }
        $upload->savePath = $savepath;// 设置附件上传目录
        if (!$upload->upload()) {// 上传错误提示错误信息
            echo json_encode(array('code' => 0, 'message' => '上传失败'));
        } else {// 上传成功 获取上传文件信息
            $info = $upload->getUploadFileInfo();
            $file_name = date('Y-m-d') . "/" . $info[0]['savename'];
            // $image = new \Think\Image();
            // $file_name = substr($info[0]['savename'], 0,strpos($info[0]['savename'], "."))."_thumb.jpg";
            // $image->open($savepath.$info[0]['savename']);// 生成一个居中裁剪为的缩略图并保存为thumb.jpg
            // $image->thumb(150, 150,\Think\Image::IMAGE_THUMB_SCALE)->save($savepath.$file_name);


            //直接存入数据库
            $data = array(
                "banner_img" => $file_name,
                "add_time" => time(),
            );
            $insert_id = M("Banner")->add($data);
            echo json_encode(array('code' => 1, 'file_name' => $file_name, 'file_id' => $insert_id));
        }
    }

    /**
     * 执行banner删除操作
     */
    public function do_delete()
    {
        $id = I("post.id", 0);
        $banner_info = M("Banner")->where("id=$id")->find();
        $res = 0;
        if (!empty($banner_info)) {
            $src = __ROOT__ . 'Public/Uploads/' . $banner_info['banner_img'];
            if (file_exists($src)) {
                unlink($src);
                $res = M("Banner")->where("id=$id")->delete();
            }
        }
        echo $res;
    }

    public function do_change_sort()
    {
        $id = I("post.id", 0);
        $sort_order = I("post.sort_order", 0);
        $res = 0;
        if (!empty($id)) {
            $res = M("Banner")->where("id=$id")->save(array("sort_order" => $sort_order));
        }
        echo $res;
    }


}